package com.woniu.controller;

//import jdk.management.resource.internal.inst.SocketOutputStreamRMHooks;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
@ServerEndpoint("/websocket")
public class Test {
    @OnOpen
    public void onOpen(Session session, EndpointConfig config) {
        log.info("WebSocket connection opened: {}", session.getId());

        // 解析查询参数（假设前端通过查询参数附带数据）
        Map<String, List<String>> parameters = session.getRequestParameterMap();
        String username = parameters.get("username") != null ? parameters.get("username").get(0) : "Guest";
        System.out.println("____________________________");
        System.out.println(username);
        // 将用户名附加到 Session 的用户属性中
        session.getUserProperties().put("username", username);

        log.info("Username from client: {}", username);
    }

    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        // 在接收到消息时检索自定义数据
        Map<String, Object> userProperties = session.getUserProperties();
        String username = (String) userProperties.get("username");
        System.out.println(message);
        log.info("Received message from client: {}", message);
        log.info("Username from session: {}", username);

        // 响应客户端
        session.getBasicRemote().sendText("Server received your message: " + message + " from " + username);
    }

    @OnClose
    public void onClose(Session session, CloseReason closeReason) {
        log.info("WebSocket connection closed: {}, Reason: {}", session.getId(), closeReason);
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        log.error("WebSocket error for session {}: {}", session.getId(), throwable.getMessage());
    }
}
